﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using NextCMS.Models;

/// <summary>
/// Summary description for BasePage
/// </summary>
public class BasePage : System.Web.UI.Page
{
	public BasePage()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public int FrontSiteId
    {
        get
        {
            string siteName = Convert.ToString(Page.RouteData.Values["SiteName"]);
            if (String.IsNullOrEmpty(siteName))
                return Convert.ToInt32(SiteSettingsHelper.GetSetting("DefaultSite", 0));
            else
            {
                using (SitesHelper helper = new SitesHelper())
                {
                    SiteModel sm = helper.GetByName(siteName);
                    if (sm == null)
                        return 0;
                    else
                        return sm.Id;
                }
            }
        }
    }
    public class SiteUserLanguage
    {
        public int SiteId { get; set; }
        public int UserLanguageId { get; set; }
    }
    public int UserLanguageId
    {
        get
        {
            int LanguageID = 0;
            if (Session["UserLanguageId"] == null)
            {
                if (Request.UserLanguages.Count() > 0)
                {
                    using (SiteLanguagesHelper helper = new SiteLanguagesHelper())
                    {
                        foreach (string LangCode in Request.UserLanguages)
                        {

                            SiteLanguageModel sm = helper.GetByLangCode(LangCode,FrontSiteId);
                            if (sm != null)
                                LanguageID = sm.Id;
                            else if (LangCode.Contains("-"))
                            {
                                sm = helper.GetByLangCode(LangCode.Split('-')[0], FrontSiteId);
                                if (sm != null)
                                    LanguageID = sm.Id;
                            }
                            if (LanguageID > 0)
                                break;
                        }
                        if(LanguageID==0)
                        LanguageID = helper.GetAllBySiteId(FrontSiteId).FirstOrDefault().Id;
                    }
                    

                }
                else
                {
                    using (SiteLanguagesHelper helper = new SiteLanguagesHelper())
                    {
                        LanguageID = helper.GetAllBySiteId(FrontSiteId).FirstOrDefault().Id;
                    }
                }
                SiteUserLanguage siteUserLanguage = new SiteUserLanguage();
                siteUserLanguage.SiteId = FrontSiteId;
                siteUserLanguage.UserLanguageId = LanguageID;
                Session["UserLanguageId"] = siteUserLanguage;
            }
            else
            {
                SiteUserLanguage siteUserLanguage =Session["UserLanguageId"] as  SiteUserLanguage;
                if (siteUserLanguage.SiteId == FrontSiteId)
                    LanguageID = siteUserLanguage.UserLanguageId;
                else
                {
                    Session["UserLanguageId"] = null;
                    LanguageID = UserLanguageId;
                }
            }
            return LanguageID;
        }
    }
    public void LoadCss(string rootFolder)
    {
        List<string> lstCssFiles = new List<string>();
        GetAllFilesByExtension(rootFolder, ".css", lstCssFiles);
        foreach (string css in lstCssFiles)
        {
            string cssFile = css.Substring(css.IndexOf(rootFolder), css.Length - css.IndexOf(rootFolder));
            AddCssLink("Templates/"+cssFile);
        }
    }
    public string GetAllCss(string rootFolder)
    {
        List<string> lstCssFiles = new List<string>();
        GetAllFilesByExtension(rootFolder, ".css", lstCssFiles);
        string CSS = "";
        foreach (string css in lstCssFiles)
        {
            string cssFile = css.Substring(css.IndexOf(rootFolder), css.Length - css.IndexOf(rootFolder));
            cssFile = ResolveClientUrl("~/Templates/" + cssFile);
            CSS = CSS == "" ? cssFile : cssFile + ", " + CSS;
        }
        return CSS;
    }
    public void LoadJavascript(string rootFolder)
    {
        List<string> lstJsFiles = new List<string>();
        GetAllFilesByExtension(rootFolder, ".js", lstJsFiles);
        int i = 1;
        foreach (string js in lstJsFiles)
        {
            string jsFile = js.Substring(js.IndexOf(rootFolder), js.Length - js.IndexOf(rootFolder));
            Page.ClientScript.RegisterClientScriptInclude(Page.GetType(), "JS"+i, ResolveClientUrl("~/Templates/" + jsFile));
            i++;
        }
    }
    public void GetAllFilesByExtension(string rootFolder, string extension, List<string> lstFiles)
    {
        string FullPath = Server.MapPath("~") + "/Templates/" + rootFolder;
        string[] Files = Directory.GetFiles(FullPath);
        lstFiles.AddRange(Files.Where(c => Path.GetExtension(c).ToLower() == extension));
        string[] Directorys = Directory.GetDirectories(FullPath);
        
        

        foreach (string dir in Directorys)
        {
            DirectoryInfo di = new DirectoryInfo(dir);
            GetAllFilesByExtension(rootFolder + "/" + di.Name, extension, lstFiles);
        }
    }
    public void AddCssLink(string cssfile)
    {
        HtmlGenericControl css;
        css = new HtmlGenericControl();
        css.TagName = "link";
        css.Attributes.Add("type", "text/css");
        css.Attributes.Add("rel", "stylesheet");
        css.Attributes.Add("href", ResolveClientUrl("~/" + cssfile));

        Page.Header.Controls.Add(css);
    }

    public void ResizeImage(string filePath,int width,int height, Stream fromStream)
    {

        var image = Image.FromStream(fromStream);

        var newWidth = width;

        var newHeight = height;

        var thumbnailBitmap = new Bitmap(newWidth, newHeight);



        var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);

        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;

        thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;

        thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;



        var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

        thumbnailGraph.DrawImage(image, imageRectangle);



        thumbnailBitmap.Save(filePath, image.RawFormat);
        thumbnailGraph.Dispose();
        thumbnailBitmap.Dispose();
        image.Dispose();
    }

    protected override void OnPreInit(EventArgs e)
    {
        string LangCode = Convert.ToString(Request.QueryString["Lang"]);
        if (!String.IsNullOrEmpty(LangCode))
        {
            SiteLanguageModel slm = ApplicationCache.SiteLanguages.Where(c => c.LangCode.ToLower() == LangCode.ToLower() && c.SiteId == FrontSiteId).FirstOrDefault();
            if (slm != null)
            {
                SiteUserLanguage siteUserLanguage = new SiteUserLanguage();
                siteUserLanguage.SiteId = FrontSiteId;
                siteUserLanguage.UserLanguageId = slm.Id;
                Session["UserLanguageId"] = siteUserLanguage;
            }
        }
        base.OnPreInit(e);
    }

}